/*
 * 客户权限首页展示
 * @Author: ljb
 * @Date: 2018-05-15 16:54:33
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-10-29 10:02:23
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>

    .v-home-customer-views {
        padding: 0 5px 5px 5px;
        .chart {
			height: 300px;
		}
		.radius-card {
			position: relative;
			border-radius: 5px;
		}
		.card-title {
			height: 32px;
			line-height: 32px;
			font-size: 20px;
		}
		.table-list {
			margin-top: 20px;
			.sc-card {
				box-shadow: 0 0 1px 0 rgba(0,0,0,.1);
			}
		}
		/*修改select的宽度*/
		.store-form {
			overflow: hidden;
			.store-select {
				position: absolute;
				right: 35px;
				width: 200px;
				z-index: 100;
			}
		}
		/*修改select的宽度 END*/
	}
	#age_pine_chart,
	#gender_pine_chart,
	#city_pine_chart{
		width: 400px;
	}

</style>
<template>
	<div class="v-home-customer-views">
		<Card
			class="radius-card"
			dis-hover>
			<p
				slot="title"
				class="card-title">
				<i class="admin__icon user"/>
				<span>{{ $t('home.page_title') }}</span>
			</p>
			<Row
				v-show="hasProfiles"
				class="table-list"
				type="flex"
				justify="space-around">
				<i-col
					span="7">
					<div
						v-show="hasBornRange"
						id="age_pine_chart"
						class="chart"/>
					<empty-chart
						v-show="!hasBornRange"
						:title="$t('home.age_distribution')"/>
				</i-col>
				<i-col
					span="7">
					<div
						v-show="hasCityArea"
						id="city_pine_chart"
						class="chart"/>
					<empty-chart
						v-show="!hasCityArea"
						:title="$t('home.city_distribution')"/>
				</i-col>
				<i-col
					span="7">
					<div
						v-show="hasSexRatio"
						id="gender_pine_chart"
						class="chart"/>
					<empty-chart
						v-show="!hasSexRatio"
						:title="$t('home.gender_distribution')"/>
				</i-col>
			</Row>
			<empty
				v-show="!hasProfiles"
				:image-width="150"
				:height="320"/>
		</Card>

		<Row
			:gutter="20"
			type="flex"
			justify="space-between">
			<i-col
				span="12"
				class="table-list">
				<Card
					class="radius-card"
					dis-hover>
					<p
						slot="title"
						class="card-title">
						<i class="admin__icon visit"/>
						<span>{{ $t('home.skin_test_statistics') }}</span>
					</p>

					<div v-if="skin_record_counts.length > 0">
						<all-skin-test-search-form
							position="right"
							@search="confirmSearch"/>

						<!-- 人流量统计折线图 -->
						<all-skin-test-line-chart
							:loading="all_skin_test_loading"
							:data-type="query.group_type"
							:skin-statistics="skin_record_counts"
							type="store"/>
					</div>

					<empty
						v-else
						:image-width="150"
						:height="406"/>
				</Card>
			</i-col>
			<i-col
				span="12"
				class="table-list">
				<!-- 测肤统计 -->
				<Card
					class="radius-card"
					dis-hover>
					<p
						slot="title"
						class="card-title">
						<i class="admin__icon skin-test"/>
						<span>{{ $t('home.store') + $t('home.skin_test_statistics') }}</span>
					</p>
					<template v-if="store_count_skin.length>0">
						<!-- 测肤统计的店铺图 -->
						<!-- <skin-line-chart
						:loading="skin_test_loading"
						:data-type="query.group_type"
						:skin-statistics="store_count_skin"
						type="store"/> -->
						<div class="store-form">
							<skin-search-form
								@search="confirmSearchSkinTest"/>
							<Select
								v-model="current_store"
								class="store-select">
								<Option
									v-for="store in store_count_skin"
									:value="store.id"
									:key="store.id">
									{{ store.name }}
								</Option>
							</Select>
						</div>

						<!-- 测肤统计的店铺柱状图 -->
						<skin-bar-chart
							:loading="skin_test_loading"
							:data-type="skin_query.group_type"
							:skin-statistics="currentStoreSkinTest"
							type="store"/>
					</template>

					<empty
						v-else
						:image-width="150"
						:height="406"/>

				</Card>
			</i-col>
		</Row>

		<Row
			:gutter="20"
			type="flex"
			justify="space-between">
			<i-col
				span="12"
				class="table-list">
				<Card
					class="radius-card"
					dis-hover>
					<p
						slot="title"
						class="card-title">
						<i class="admin__icon store-list"/>
						<span>{{ $t('home.store_list') }}</span>
					</p>
					<store-index
						v-if="stores.length>0"
						:loading="table_loading"
						:stores="stores"/>
					<empty
						v-else
						:image-width="150"
						:height="350"/>
				</Card>
			</i-col>
			<i-col
				span="12"
				class="table-list">
				<Card
					class="radius-card"
					dis-hover>
					<p
						slot="title"
						class="card-title">
						<i class="admin__icon hot-makeup"/>
						<span>{{ $t('home.product_list') }}</span>
					</p>

					<!-- 产品列表 -->
					<product-index
						v-if="products.length>0"
						:loading="table_loading"
						:products="products"
						@detail="watchProductMakeupDetail"/>
					<empty
						v-else
						:image-width="150"
						:height="350"/>

				</Card>
			</i-col>
		</Row>

		<Modal
			v-model="makeup_detail_modal"
			class-name="vertical-middle-modal">
			<p
				slot="header"
				class="modal-title-center">{{ $t('home.makeup_detail') }}</p>
			<!-- 淘宝详情编辑组件 -->
			<product-store-index
				:store-makeup-lists="product_store_makeup_list"/>

			<div slot="footer"/>

		</Modal>

	</div>
</template>

<script>

import API_LIST from 'src/API_LIST';
import qs from 'qs';

import echarts from 'echarts';

import allSkinTestSearchForm from 'src/views/component/all-skin-test-search-form';
import allSkinTestLineChart from 'src/views/component/all-skin-test-line-chart';

import skinSearchForm from 'src/views/component/skin-search-form';
import skinBarChart from 'src/views/component/skin-bar-chart';
import empty from 'src/views/component/empty';
import emptyChart from 'src/views/component/empty-chart';

import { i18n } from 'src/i18n/index';

import storeIndex from './store-index';
import productIndex from './product-index';
import productStoreIndex from './product-store-index';


export default {
	name: 'CustomerHome',
	components: {
		storeIndex,
		productIndex,
		productStoreIndex,
		allSkinTestLineChart,
		allSkinTestSearchForm,
		skinBarChart,
		skinSearchForm,
		empty,
		emptyChart,
	},
	data() {
		return {

			gender_map: {
				0: this.$t('home.unknown'),
				1: this.$t('home.male'),
				2: this.$t('home.female'),
			},

			query: {
				group_type: 'day',
			},		// 综测肤次数统计的搜索参数

			skin_query: {
				group_type: 'day',
			},		// 测肤统计的搜索参数

			skin_record_counts: [], // 综测肤次数统计

			stores: [], // 店铺列表

			products: [], // 产品列表

			profiles: {}, // 饼图展示

			age_pine: null, // 年龄饼图

			city_pine: null, // 城市饼图

			gender_pine: null, // 性别饼图

			table_loading: false, // 表格加载

			all_skin_test_loading: false, // 总测肤统计折线图加载

			skin_test_loading: false, // 测肤统计图加载

			store_count_skin: [],	// 所有店铺的测肤统计

			device_account_count_skin: [],	// 所有设备的测肤统计

			current_store: '',		// 当前选中的店铺

			product_store_makeup_list: [],	// 产品的店铺试妆次数列表

			makeup_detail_modal: false,		// 试妆详情模态框的显隐控制
		};
	},
	computed: {
		currentStoreSkinTest() {
			const current_store = this.store_count_skin.filter(store => store.id === this.current_store);
			return current_store || [];
		},

		hasBornRange() {
			return Array.isArray(this.profiles.born_range) && this.profiles.born_range.length > 0;
		},

		hasCityArea() {
			return Array.isArray(this.profiles.city_area) && this.profiles.city_area.length > 0;
		},

		hasSexRatio() {
			return Array.isArray(this.profiles.sex_ratio) && this.profiles.sex_ratio.length > 0;
		},

		hasProfiles() {
			return this.hasBornRange || this.hasCityArea || this.hasSexRatio;
		},

	},
	mounted() {
		this.age_pine = echarts.init(document.getElementById('age_pine_chart'));
		this.city_pine = echarts.init(document.getElementById('city_pine_chart'));
		this.gender_pine = echarts.init(document.getElementById('gender_pine_chart'));

		this.fetchDashboard()
			.then(this.setOptionLoop);

		this.fetchSkintTestCount(this.query);
		this.fetchSkinTestStatistics(this.skin_query);
	},
	methods: {
		/**
         * 初始化饼图
         * @param  {string} series_name {饼图名称}
         * @param  {array} legend_data {饼图选项数组}
         * @param  {array} series_data {饼图展示数据数组}
         * @param  {array} color {饼图颜色数组}
         * @param  {Object} chart       {需要进行初始化的饼图}
         * @return {undefined}
         */
		initPineChart({
			series_name, legend_data, series_data, color,
		}, chart) {
			const unit = i18n.t('home.people');
			const option = {
				title: {
					text: series_name,
					left: 'center',
				},
				legend: {
					// height: 300,
					type: 'scroll',
					orient: 'vertical',
					x: 'left',
					data: legend_data,
				},
				series: [
					{
						name: series_name,
						type: 'pie',
						radius: ['50%', '70%'],
						avoidLabelOverlap: false,
						clockwise: false,
						label: {
							normal: {
								show: false,
								position: 'center',
								formatter: [
									'{b}',
									`{c}${unit}`,
								].join('\n'),
							},
							emphasis: {
								show: true,
								textStyle: {
									fontSize: 30,
									fontWeight: 'bold',
								},
							},
						},
						labelLine: {
							normal: {
								show: false,
							},
						},
						tooltip: {
							'backgroundi-color': 'blue',
						},
						data: series_data,
						color,
					},
				],
			};

			chart.setOption(option);

			chart.hideLoading();
		},

		/**
         * 循环设置并初始化饼图选项
         * @return {undefined}
         */
		setOptionLoop() {
			const self = this;

			const keys = Object.keys(this.profiles);

			for (let i = 0; i < keys.length; i += 1) {
				const key = keys[i];
				const profile = self.profiles[key];

				const pine_option = {
					series_name: '',
					legend_data: [],
					series_data: [],
				};

				let chart = null;

				switch (key) {
				case 'born_range':

					profile.forEach((born) => {
						const param = {
							value: born.count,
							name: born.range,
						};

						pine_option.series_data.push(param);
						pine_option.legend_data.push(born.range);
					});

					pine_option.series_name = i18n.t('home.age_distribution'); // '年龄';

					pine_option.color = ['#8278e9', '#96bfff', '#37a2da', '#e7bcf2', '#66e0e3'];

					chart = self.age_pine;

					break;
				case 'city_area':

					profile.forEach((item) => {
						const param = {
							value: item.count,
							name: item.city,
						};

						pine_option.series_data.push(param);
						pine_option.legend_data.push(item.city);
					});

					pine_option.series_name = i18n.t('home.city_distribution'); //  '城市';

					pine_option.color = ['#8278e9', '#96bfff', '#37a2da', '#61dee1', '#e7bcf2', '#ffc2ec', '#ff859c', '#fcbf55', '#ffd180', '#575bec', '#575bec', '#575bec', '#575bec', '#cd97ff', '#cd97ff', '#cd97ff', '#cd97ff', '#6db8f2', '#ec6f7b', '#ec6f7b', '#fab1d4', '#f89686', '#f8d3ac', '#e8b3af', '#e8b3af', '#ee8e7e', '#e7bcf2', '#f785a5', '#ffcdb4', '#94d3ed', '#ee8cd1', '#84c5dd', '#b1e094', '#a8ace7'];

					chart = self.city_pine;

					break;

				default:

					profile.forEach((sex) => {
						const param = {
							value: sex.count,
							name: self.gender_map[sex.sex],
						};

						pine_option.series_data.push(param);
						pine_option.legend_data.push(self.gender_map[sex.sex]);
					});

					pine_option.series_name = i18n.t('home.gender_distribution'); //  '性别';

					pine_option.color = ['#8278e9', '#96bfff', '#e7bcf2'];

					chart = self.gender_pine;

					break;
				}

				setTimeout(() => {
					self.initPineChart(pine_option, chart);
				}, 1000 * (i + 1));
			}
		},

		/**
         * 获取首页数据
         * @return {undefined}
         */
		fetchDashboard() {
			this.table_loading = true;

			this.age_pine.showLoading({
				color: '#8278e9',
			});
			this.city_pine.showLoading({
				color: '#8278e9',
			});
			this.gender_pine.showLoading({
				color: '#8278e9',
			});

			return this.$http.get(API_LIST.CUSTOMER_HOME_DATA)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.stores = data.stores;
					// this.wechat_users = data.wechat_users;
					this.products = data.products;
					// this.visits = data.visits;
					this.profiles = data.profiles;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.table_loading = false; });
		},

		/**
		 *确认搜索
		 *@param {String} group_type {搜索对象}
		 */
		confirmSearch({ group_type }) {
			this.query.group_type = group_type || 'month';

			this.fetchSkintTestCount(this.query);
		},

		/**
		 *确认搜索
		 *@param {String} group_type {搜索对象}
		 */
		confirmSearchSkinTest({ group_type }) {
			this.skin_query.group_type = group_type || 'month';

			this.fetchSkinTestStatistics(this.skin_query);
		},

		/**
		 * 查看产品试妆详情
		 * @param  {String} id {产品id}
		 * @return {undefined}
		 */
		watchProductMakeupDetail(id) {
			const product_makeup_detail = this.products.filter(product => product.id === id)[0] || {};
			this.product_store_makeup_list = product_makeup_detail.stores;

			this.makeup_detail_modal = true;
		},

		/**
		 * 获取访客统计数据
		 * @param {Object} param {访客统计传参对象}
		 * @return {undefined}
		 */
		fetchGetVisitCounts(param) {
			this.visit_loading = true;

			const query = qs.stringify(param);

			this.$http.get(`${API_LIST.CUST_HOME_VISIT_COUNTS}?${query}`)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.visit_statistics = data.visit_counts.reverse();
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.visit_loading = false; });
		},

		/**
		 * 获取所有的测肤次数统计
		 * @param  {Object} param {请求测肤次数接口的参数}
		 * @return {type} {description}
		 */
		fetchSkintTestCount(param) {
			this.all_skin_test_loading = true;

			const query = qs.stringify(param);

			this.$http.get(`${API_LIST.CUST_ALL_SKIN_STATISTIC}?${query}`)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.skin_record_counts = data.skin_record_counts.reverse();
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.all_skin_test_loading = false; });
		},

		/**
		 * 获取测肤统计（按店铺分）
		 * @param {Object} param {测肤统计传参对象}
		 * @return {undefined}
		 */
		fetchSkinTestStatistics(param) {
			this.skin_test_loading = true;

			const query = qs.stringify(param);

			this.$http.get(`${API_LIST.CUST_SKIN_STATISTIC}?${query}`)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.store_count_skin = data.store_count_skin;
					this.device_account_count_skin = data.device_account_count_skin;

					this.current_store = data.store_count_skin.length > 0 ? data.store_count_skin[0].id : 0;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.skin_test_loading = false; });
		},

	},
};
</script>
